package com.jiahe.blog.common.handler;

import com.alibaba.fastjson.JSON;
import com.jiahe.blog.model.StatusConst;
import com.jiahe.blog.model.response.BlogResponse;
import com.jiahe.blog.utils.ServletUtils;
import com.jiahe.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 用户未登录处理
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String msg = StringUtils.format("请求访问：{}，" + e.getMessage(), request.getRequestURI());
        log.error(msg);
        ServletUtils.renderString(response, JSON.toJSONString(BlogResponse.error(StatusConst.NOT_LOGIN, msg)));
    }
}
